

$(function () {
  // scan user to delet
  const csrf = $('input[name="csrfmiddlewaretoken"]').val()
  function getCheckUser(username_b64) {
    data = new FormData()
    data.append("username", username_b64)
    data.append("check_state", "delete")
    return axios.post(getCheckUser_url, data,
      {
        headers: {
          "X-CSRFTOKEN": csrf
        }
      })

  }

  let gnsScan = new GnsScan(
    content => {
      getCheckUser(content).then(response => {
        data = response.data
        if (!data.ack) {
          gnsScan.setAlert(data.err)
          return
        }

        $('#dataAction').val('delete')
        $('#eform').trigger('submit')
        
        gnsScan.close()
        // setUI(data.username)
        // setUser_id(data.user_id)

      })
    },title='Scan Staff QRCode to DELETE Form'
  )

  $('#btn-scan-imte').on('click', function () {
    $('#scan_modal').modal('toggle')
    instascan()
  })
  var deleteConfirm = new Confirm({
    body: "Type <strong>\"DELETE\"</strong> to delete the form.",
    type: 'prompt'
  })

  var doneConfirm = new Confirm({
    body: "Are you confirm to change the state of the form to DONE?"
  })

  const socket = io.connect(`${OCR_DECTECTION_IP}:5000`)
  const psu_current = $('#psu-current')
  const psu_voltage = $('#psu-voltage')
  const meter = $('#meter')
  let fetchReading = _ => setInterval(_ => {
    socket.emit('DetectionValues', data => {
      psu_v = data.psu.split(';')
      console.log(psu_v)
      psu_current.html(psu_v[0])
      psu_voltage.html(psu_v[1])
      meter.html(data.meter)
    })
  }, 300)
  socket.on('connect', _ => {
    fetchReading()
  })
  Formio.icons = 'fontawesome';
  Formio.createForm(document.getElementById('formio'),
    dataJson
  ).then(function (form) {
    var is_zoom = false
    var last_scroll_pos = 0
    function trigger_zoom() {

      return new Promise((resolve, reject) => {
        if (!is_zoom) {
          last_scroll_pos = $(window).scrollTop()
          $('#zoom-fa').removeClass("fa-search-minus")
          $('#zoom-fa').addClass("fa-search-plus")
          $('#eform_container').css("zoom", "33%")
          $('#eform_container').css("padding-left", "33%")
          $('#eform_container').css("padding-right", "33%")
          $(window).scrollTop($("#eform_container").offset().top)
        } else {
          $('#zoom-fa').removeClass("fa-search-plus")
          $('#zoom-fa').addClass("fa-search-minus")
          $('#eform_container').css("zoom", "100%")
          $('#eform_container').css("padding-left", "")
          $('#eform_container').css("padding-right", "")
        }
        is_zoom = !is_zoom

        resolve(!is_zoom)
      });
    }
    $('#btn-zoom').on('click', function () {
      trigger_zoom().then(is_zoom => {
        if (is_zoom) {
          $(window).scrollTop(last_scroll_pos)
        }
      })
      // is_zoom = !is_zoom
    })

    $('input, textarea , .form-control, .input-group').on('click', function (e) {
      if (is_zoom) {
        trigger_zoom().then(iz => {
          $('html').animate(
            {
              scrollTop: $(this).offset().top * 0.8
            },
            800
          );
          $(this).focus()
        })
      }
    })

    form.submission = {
      data: data
    }


    // // console.log(form._data)
    // $('#log-data').on('click',function(e){

    //   console.log(form.submission)
    //   form.validator.validate()
    //   coms = form.components
    //   for (let index = 0; index < coms.length; index++) {
    //     const com = coms[index];
    //     if (com.validator.validate() == false){
    //       com.scrollIntoView()
    //       com.focus()
    //     }
    //   }
    //   // console.log(form)
    // })

    $('.c-btn-s').on('click', function (e) {
      $("#id_finding_opt").attr("required", true);
      var action = $(this).val()
      console.log(form)
      console.log(form._data)
      var dataJson_str = JSON.stringify(form._data)
      console.log(dataJson_str)
      $('#dataJson').val(dataJson_str)
      if (action == 'done') {
        doneConfirm.show(() => {
          //CHECK REMARK FIELD
          // console.log(validateForm());
          var remark_ok = validateForm();

          // check formio
          if (form.checkValidity(null, true) == false || remark_ok == false) {
            // scroll to invalid
            invalid = $('.is-invalid')[0]
            if (invalid) {
              invalid.focus()
            }
            return
          }
          // if(!form.checkValidity()){
          //   setTimeout(_=>form.reportValidity(),100)
          // }
          // return
          // check submit form
          let fm = document.getElementById('eform')
          if (!fm.checkValidity()) {
            setTimeout(_ => fm.reportValidity(), 100)
            return
          }
          $('#dataAction').val(action)
          $('#overall_test_result').val($('input[name="overall_test_result_radio"]:checked').val())
          $('#eform').trigger('submit')
        }, (bo) => {
          return bo
        })
      } else {
        $('#dataAction').val(action)
        $('#overall_test_result').val($('input[name="overall_test_result_radio"]:checked').val())
        $('#eform').trigger('submit')
      }
    })



    $('button[type="submit"]').on('click', function (e) {
      console.log(form.schema)
      e.preventDefault()
    })



    $('#btn-delete').on('click', _ => {
      gnsScan.instascan()
      // deleteConfirm.show(function(b,p){
      //   console.log('new call back')
      //   if (p=='DELETE'){
      //     // $('#dataJson').val(dataJson_str)
      //     $('#dataAction').val('delete')

      //     $('#eform').trigger('submit')
      //   }
      // })


      // delete_str = prompt('Type DELETE to delete the form !')
      // if (delete_str == 'DELETE'){
      //   dataJson_str = JSON.stringify(form._data)
      //   console.log(dataJson_str)

      // }

    })


    let focused = false;
    $('input').on('focus', function () {
      focused = $(this)

    })
    $('.ims-capture').on('click', function (e) {
      captureValue = $(this).html().trim()
      if (focused.is('[readonly]') || focused.hasClass("wo-fields")) {
        alert("Field is readonly")
        return
      }

      // focused.val(captureValue)
      // focused.trigger('change')
      form.getComponent(focused.attr('name').match(/data\[([^)]+)\]/)[1]).setValue(captureValue);

      key = focused.attr('id').split('-').pop()
      if (form._data.hasOwnProperty(key)) {
        form._data[key] = captureValue
      }
    })
  });




})